package burubaka.controller.mypage;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import net.arnx.jsonic.JSON;

import org.apache.commons.lang3.StringUtils;
import org.slim3.controller.Navigation;
import org.slim3.util.ApplicationMessage;
import org.slim3.util.BeanUtil;

import burubaka.BurubakaConstants;
import burubaka.common.controller.Controller;
import burubaka.model.Tipster;
import burubaka.service.TipsterService;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class TipsterController extends Controller {

	private static final Logger log = Logger.getLogger(TipsterController.class.getName());
	private TipsterService tipsterService = new TipsterService();

	@Override
	public Navigation init() throws Exception {

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String userId = user.getUserId();
		Tipster tipster = tipsterService.findByUser(userId);
		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("tipster", tipster);
		String json = JSON.encode(resMap, true);
		log.fine(json);
		setJson(json);

		return null;
	}

	/**
	 * 登録
	 * 
	 * @return Navigation
	 * @throws Exception
	 */
	public Navigation regist() throws Exception {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		String userId = user.getUserId();
		Tipster tipster = tipsterService.findByUser(userId);

		Map map = JSON.decode((String) reqMap.get("tipster"), HashMap.class);
		BeanUtil.copy(map, tipster);

		String labelNickname = ApplicationMessage.get(BurubakaConstants.LABEL_NICKNAME, null);
		if (StringUtils.isEmpty(tipster.getNickname())) {
			String msg = ApplicationMessage.get(BurubakaConstants.VALIDATOR_REQUIRED, labelNickname);
			setErrorJson(msg);
			return null;
		}

		if (tipster.getNickname().length() > BurubakaConstants.MAX_LEN_NICKNAME) {
			String msg = ApplicationMessage.get("validator.maxlen", labelNickname, BurubakaConstants.MAX_LEN_NICKNAME);
			setErrorJson(msg);
			return null;
		}

		tipsterService.regist(tipster);

		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put(BurubakaConstants.RESPONSEKEY_MESSAGE,
				ApplicationMessage.get(BurubakaConstants.MESSAGEKEY_REG_SUCCESS, null));
		setJson(JSON.encode(resMap, true));

		return null;
	}

	/**
	 * アップロード
	 * 
	 * @return Navigation
	 * @throws Exception
	 */
	public Navigation upload() throws Exception {

		return null;
	}
}
